package com.forum.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

import com.forum.model.dao.PostDAO;
import com.forum.model.dao.TopicDAO;
import com.forum.model.pojo.Topic;

@WebFilter("/topic.jsp")
public class TopicFilter implements Filter {
	public void init(FilterConfig fConfig) throws ServletException {}

	public void destroy() {}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		String id = request.getParameter("id");
		
		if(id != null){
			long topicId = new Long(id);
			Topic t = new TopicDAO().getObjectById(topicId);
			if(t != null){
				t.setPosts(new PostDAO().getAll(topicId));
				request.setAttribute("topic", t);
				chain.doFilter(request, response);
				return;
			}
		}
		
		RequestDispatcher dispatcher = request.getRequestDispatcher("/index.jsp");
		dispatcher.forward(request, response);
	}
}